<template>
  <div class="user-info-bar">
    <div class="user-info-content">
      <template v-if="user">
        <div class="user-avatar">{{ user.username.charAt(0).toUpperCase() }}</div>
        <div class="user-details">
          <span class="username">{{ user.username }}</span>
          <span class="welcome-text">欢迎回来</span>
        </div>
        <button class="logout-btn" @click="logout">
          <span class="logout-icon">🚪</span>
          <span>退出</span>
        </button>
      </template>
      <template v-else>
        <button class="login-btn" @click="goLogin">
          <span class="login-icon">🔑</span>
          <span>请登录</span>
        </button>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()

const user = ref(null)// 存储当前用户信息（null表示未登录）
// 从localStorage加载用户信息
function loadUser() {
  const u = localStorage.getItem('user')
  user.value = u ? JSON.parse(u) : null
}
// 跳转到登录页
function goLogin() {
  router.push('/login')
}
// 退出登录
function logout() {
  localStorage.removeItem('user')// 清除本地存储
  user.value = null // 重置用户状态
  location.reload()  // 刷新页面（可选）
}
onMounted(() => {
  loadUser()// 组件挂载时加载用户信息
  window.addEventListener('user-login', loadUser)//并监听全局事件 user-login（例如其他组件登录成功后触发）。
})
onUnmounted(() => {
  window.removeEventListener('user-login', loadUser)// 组件卸载时移除监听
})
</script>

<style scoped>
.user-info-bar {
  padding: 1rem 2rem;
  background-color: white;
  border-bottom: 1px solid var(--color-border);
  box-shadow: var(--shadow-sm);
}

.user-info-content {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 1.125rem;
  margin-right: 0.75rem;
  box-shadow: var(--shadow-sm);
}

.user-details {
  display: flex;
  flex-direction: column;
  margin-right: 1rem;
}

.username {
  font-weight: 600;
  color: var(--neutral-800);
}

.welcome-text {
  font-size: 0.75rem;
  color: var(--neutral-500);
}

.logout-btn, .login-btn {
  display: flex;
  align-items: center;
  padding: 0.5rem 1rem;
  border-radius: var(--radius);
  font-weight: 500;
  transition: all 0.2s;
}

.logout-btn {
  background-color: var(--neutral-100);
  color: var(--neutral-700);
  border: 1px solid var(--neutral-200);
}

.logout-btn:hover {
  background-color: var(--neutral-200);
}

.login-btn {
  background-color: var(--primary-color);
  color: white;
  border: none;
}

.login-btn:hover {
  background-color: var(--primary-dark);
}

.logout-icon, .login-icon {
  margin-right: 0.5rem;
  font-size: 1rem;
}

@media (max-width: 768px) {
  .user-info-bar {
    padding: 0.75rem 1rem;
  }
  
  .welcome-text {
    display: none;
  }
}
</style>